package com.example.viewpager2demo

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout

class PageAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
    private val fragments = mutableListOf<Fragment>()
    private var tabLayout: TabLayout? = null
    private val fragmentTags = mutableMapOf<Int, String>()

    override fun getItemCount(): Int = fragments.size

    override fun createFragment(position: Int): Fragment = fragments[position]

    fun setTabLayout(tabLayout: TabLayout) {
        this.tabLayout = tabLayout
    }

    fun addFragment(fragment: Fragment) {
        fragments.add(fragment)
        fragmentTags[fragments.size - 1] = generateFragmentTag(fragment)
        notifyItemInserted(fragments.size - 1)
        tabLayout?.getTabAt(fragments.size - 1)?.setText("页面 ${fragments.size}")
    }

    fun removeFragment(position: Int) {
        if (position in 0 until fragments.size) {
            fragments.removeAt(position)
            fragmentTags.remove(position)
            // 更新剩余Fragment的标签
            for (i in position until fragments.size) {
                fragmentTags[i] = generateFragmentTag(fragments[i])
            }
            notifyItemRemoved(position)
            for (i in position until fragments.size) {
                tabLayout?.getTabAt(i)?.setText("页面 ${i + 1}")
            }
        }
    }

    // 更新指定位置的Fragment
    fun updateFragment(position: Int, newFragment: Fragment) {
        if (position in 0 until fragments.size) {
            fragments[position] = newFragment
            fragmentTags[position] = generateFragmentTag(newFragment)
            notifyItemChanged(position)
        }
    }

    // 重新排序Fragment
    fun reorderFragments(newOrder: List<Int>) {
        if (newOrder.size != fragments.size) return

        val newFragments = mutableListOf<Fragment>()
        val newTags = mutableMapOf<Int, String>()
        
        newOrder.forEachIndexed { newIndex, oldIndex ->
            if (oldIndex in 0 until fragments.size) {
                newFragments.add(fragments[oldIndex])
                newTags[newIndex] = generateFragmentTag(fragments[oldIndex])
            }
        }

        fragments.clear()
        fragments.addAll(newFragments)
        fragmentTags.clear()
        fragmentTags.putAll(newTags)
        
        notifyDataSetChanged()
        
        // 更新TabLayout的标题
        fragments.forEachIndexed { index, _ ->
            tabLayout?.getTabAt(index)?.setText("页面 ${index + 1}")
        }
    }

    private fun generateFragmentTag(fragment: Fragment): String {
        return "fragment_${fragment.hashCode()}"
    }

    // 获取Fragment的标签
    fun getFragmentTag(position: Int): String? {
        return fragmentTags[position]
    }
} 